<template>
  <div id="subMenus" class="unselect">
    <section class="menu-title">
      <span>{{ currentTopMenu.name }}</span>
    </section>
    <a-menu
      mode="inline"
      :selectedKeys="selectedMenu"
      v-model:openKeys="openedMenu"
      @select="onMenuSelect"
      class="menu-list hide-scroller-bar"
      :inlineIndent="0"
    >
      <template v-for="item in menuList" :key="item.alias">
        <template v-if="!item.children || !item.children.length">
          <a-menu-item :key="item.alias">
            <!-- <template #icon v-if="item.icon">
              <cu-icon :type="item.icon"></cu-icon>
            </template> -->
            <span>{{ item.name }}</span>
            <cu-icon
              type="org-caozuo-wailian"
              v-if="item.url_type == 'target_url'"
              :style="{
                marginLeft: '16px',
                color: 'rgba(0, 0, 0, 0.6)',
                fontWeight: 'bold',
              }"
            ></cu-icon>
          </a-menu-item>
        </template>
        <template v-else>
          <!-- 递归显示菜单 -->
          <a-divider style="margin: 10px 0" />
          <sub-menu :menu-info="item" :key="item.alias" />
        </template>
      </template>
    </a-menu>
  </div>
</template>

<script>
import { computed, defineComponent, reactive, toRaw, toRefs, watch } from "vue";
import { useRoute } from "vue-router";
import RouteUtils from "../../router/router.utils";
import store from "../../store";

const SubMenu = {
  name: "SubMenu",
  props: {
    menuInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  template: `
      <a-sub-menu :key="menuInfo.alias">
       <template #icon v-if="menuInfo.icon">
         <cu-icon :type="menuInfo.icon"></cu-icon>
       </template>
      <template #title>
        <span style="font-size: 12px;padding-left: 16px;color: rgba(0,0,0,0.56)">{{ menuInfo.name }}</span>
        </template>
      <template v-for="item in menuInfo.children" :key="item.alias">
        <template v-if="!item.children || !item.children.length">
          <a-menu-item :key="item.alias">
            {{ item.name }}
          </a-menu-item>
        </template>
        <template v-else>
          <sub-menu :menu-info="item" :key="item.alias" />
        </template>
      </template>
    </a-sub-menu>
  `,
};

export default defineComponent({
  name: "SecondMenu",
  components: { "sub-menu": SubMenu },
  setup() {
    const route = useRoute();

    const state = reactive({
      menuList: [],
      selectedMenu: [],
      openedMenu: [],
      currentMenu: {},
      routeName: "",
    });

    /** 标记加载过的菜单 */
    const setLoadSubMenu = () => {
      store.dispatch("SetLoadedSubMenu", {
        topAlias: currentTopMenu.value.alias,
        subAlias: state.currentMenu.alias,
      });
    };

    /** 点击菜单 */
    const onMenuSelect = (e) => {
      const { key } = e;
      state.currentMenu = RouteUtils.getMenuByAlias(key, state.menuList);
      if (state.currentMenu.url_type == "target_url") {
        window.open(state.currentMenu.alias);
        return;
      }
      state.selectedMenu = [key];
      RouteUtils.onMenuChange({ menu: state.currentMenu });
      setLoadSubMenu();
      store.dispatch("SetCurrentSubMenuName", state.currentMenu);
    };

    watch(
      () => route.name,
      (name) => {
        state.routeName = name;
        getCurrentSelectedMenu(name);
      }
    );

    /** 获取当前选中子集菜单 */
    const getCurrentSelectedMenu = (name) => {
      let currentMenu = null;
      let currentMenuAlias = name;

      if (!currentMenuAlias) {
        // 当前菜单上次是否加载过
        const loadedSubMenu = store.getters.loadedSubMenu;
        currentMenuAlias = loadedSubMenu[currentTopMenu.value.alias];
      }

      if (currentMenuAlias) {
        currentMenu = RouteUtils.getMenuByAlias(
          currentMenuAlias,
          state.menuList
        );
      }

      // 没有加载过的菜单 查找当前路由是否在menuList里
      if (!currentMenu) {
        currentMenu = RouteUtils.getMenuByAlias(
          state.routeName,
          state.menuList
        );
      }

      // 如果还是没有找到该菜单，则认定为 1、当前菜单进入了子路由，保持不更新菜单选中情况 2、刷新后当前路由没有权限了
      if (!currentMenu && (!state.currentMenu || !state.currentMenu.alias)) {
        const lastSelectedMenuName = store.getters.currentSubMenuName;
        let lastMenu = null;
        if (lastSelectedMenuName) {
          lastMenu = RouteUtils.getMenuByAlias(
            lastSelectedMenuName,
            state.menuList
          );
        }
        if (lastMenu) {
          currentMenu = lastMenu;
        } else {
          currentMenu = state.menuList[0];
          RouteUtils.handleRouteEnterByApp({
            menu: currentMenu,
            enterType: "replace",
          });
          store.dispatch("SetCurrentSubMenuName", currentMenu);
        }
      }

      if (currentMenu) {
        state.selectedMenu = [currentMenu.alias];
        state.currentMenu = currentMenu;
        setLoadSubMenu();
      }
    };

    /**获取当前下级菜单 */
    const currentTopMenu = computed(() => store.getters.currentTopMenu);
    watch(
      currentTopMenu,
      (topMenu, preTopMenu) => {
        if (topMenu.alias != preTopMenu.alias) {
          state.menuList = [];
          state.currentMenu = {};
          getCurrentSubMenus();
        }
      },
      { deep: true }
    );
    const getCurrentSubMenus = (init = false) => {
      if (store.getters.isMobile) {
        return;
      }
      if (
        currentTopMenu.value &&
        currentTopMenu.value.children &&
        currentTopMenu.value.children.length
      ) {
        let { children, alias } = currentTopMenu.value;
        if (init) {
          /**
           * *【FIX】左上角切换选中项目类型后当前子菜单多语言未替换
           * * 更新一下currentTopMenu的children
           */
          const userMenu = store.getters.userMenu;
          const curTopMenu = userMenu.find((it) => it.alias == alias);
          if (curTopMenu) {
            children = curTopMenu.children;
          }
        }
        // 没有children的菜单优先展示
        let menu1 = [],
          menu2 = [];
        children.forEach((menuItem) => {
          if (menuItem.children && menuItem.children.length) {
            menu2.push(menuItem);
            state.openedMenu.push(menuItem.alias);
          } else {
            menu1.push(menuItem);
          }
        });
        state.menuList = [...menu1, ...menu2];
        state.openedMenu = state.menuList.map((item) => item.alias);
        getCurrentSelectedMenu();
      }
    };

    const init = () => {
      state.routeName = route.name;
      getCurrentSubMenus(true);
    };

    init();
    return {
      currentTopMenu,
      ...toRefs(state),
      onMenuSelect,
    };
  },
});
</script>

<style lang="less" scoped>
ul {
  margin: 0;
}
.nowrap {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
@headerHeight: 50px;
@itemHeight: 40px;
#subMenus {
  width: 100%;
  height: 100%;
  overflow: hidden;
  font-size: @font-size-base;
  box-shadow: 2px 0px 4px 0px rgba(0, 0, 0, 0.12);
  .menu-title {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 99;
    height: @headerHeight;
    line-height: @headerHeight;
    padding: 0 16px;
    overflow: hidden;
    background: #fff;
    border-bottom: 1px solid #f1f1f1;
    // color: @text-color-secondary;
    font-size: 16px;
    font-weight: bold;
    span {
      &:extend(.nowarp);
    }
  }
  .menu-list {
    position: relative;
    padding-top: @headerHeight;
    left: 0;
    z-index: 88;
    width: 100%;
    width: 100%;
    height: 100%;
    overflow-y: auto;

    &:deep(.ant-menu-sub.ant-menu-inline) {
      background: #fff;
    }
    &:deep(.ant-menu-item) {
      padding-left: 16px !important;
    }
  }
}
</style>
